import '../../../common/extension';
import { EQVersion, UNKNOWN_EQ_VERSION } from "../../base/info";
import { compareEQVersionSpecificity } from "../../base/info/env";
import { parseBasicVersion, parseRelease, parseVersion } from "../../base/info/eqVersion";
import { pathExists, readFile } from "../externalDependencies";
import * as path from 'path';
export async function getEQVersionFromPyvenvCfg(interpreterPath: string): Promise<EQVersion> {
    const configPaths = getEQvenvConfigPathsFrom(interpreterPath);
    let version = UNKNOWN_EQ_VERSION;

    // We want to check each of those locations in the order. There is no need to look at
    // all of them in parallel.
    for (const configPath of configPaths) {
        if (await pathExists(configPath)) {
            try {
                const lines = (await readFile(configPath)).splitLines();

                const eqVersions = lines
                    .map((line) => {
                        const parts = line.split('=');
                        if (parts.length === 2) {
                            const name = parts[0].toLowerCase().trim();
                            const value = parts[1].trim();
                            if (name === 'version') {
                                try {
                                    return parseVersion(value);
                                } catch (ex) {
                                    return undefined;
                                }
                            } else if (name === 'version_info') {
                                try {
                                    return parseVersionInfo(value);
                                } catch (ex) {
                                    return undefined;
                                }
                            }
                        }
                        return undefined;
                    })
                    .filter((v) => v !== undefined)
                    .map((v) => v!);

                if (eqVersions.length > 0) {
                    for (const v of eqVersions) {
                        if (compareEQVersionSpecificity(v, version) > 0) {
                            version = v;
                        }
                    }
                }
            } catch (ex) {
                // There is only ome pyvenv.cfg. If we found it but failed to parse it
                // then just return here. No need to look for versions any further.
                return UNKNOWN_EQ_VERSION;
            }
        }
    }

    return version;
}
function parseVersionInfo(versionInfoStr: string): EQVersion {
    let version: EQVersion;
    let after: string;
    try {
        [version, after] = parseBasicVersion(versionInfoStr);
    } catch {
        // XXX Use getEmptyVersion().
        return UNKNOWN_EQ_VERSION;
    }
    if (version.micro !== -1 && after.startsWith('.')) {
        [version.release] = parseRelease(after);
    }
    return version;
}


function getEQvenvConfigPathsFrom(interpreterPath: string): string[] {
    const pyvenvConfigFile = 'pyvenv.cfg';

    // Check if the pyvenv.cfg file is in the parent directory relative to the interpreter.
    // env
    // |__ pyvenv.cfg  <--- check if this file exists
    // |__ bin or Scripts
    //     |__ eq  <--- interpreterPath
    const venvPath1 = path.join(path.dirname(path.dirname(interpreterPath)), pyvenvConfigFile);

    // Check if the pyvenv.cfg file is in the directory as the interpreter.
    // env
    // |__ pyvenv.cfg  <--- check if this file exists
    // |__ eq  <--- interpreterPath
    const venvPath2 = path.join(path.dirname(interpreterPath), pyvenvConfigFile);

    // The paths are ordered in the most common to least common
    return [venvPath1, venvPath2];
}